package cn.me.alphamq.common.util;

import java.io.*;

/**
 * 简化文件读写的工具类
 *
 * @author f
 */
public class FileUtil {

    /**
     * 创建文件
     *
     * @param dirPath  文件的目录的路径
     * @param fileName 文件名
     */
    public static void createFile(String dirPath, String fileName) {
        String newFilePath = dirPath + fileName;
        File dir = new File(dirPath);
        File newFile = new File(newFilePath);
        try {
            // 先（递归）创建目录
            dir.mkdirs();
            // 再创建文件
            newFile.createNewFile();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 将文件内容以字符串的方式读出来
     *
     * @param path
     * @return
     */
    public static String readFromFile(String path) {
        try (BufferedReader in = new BufferedReader(new FileReader(path))) {
            StringBuffer buffer = new StringBuffer();
            while (in.ready()) {
                buffer.append(in.readLine());
            }
            return buffer.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 将内容覆盖写入文件
     *
     * @param path
     * @param content
     */
    public static void overWriteToFile(String path, String content) {
        try (BufferedWriter out = new BufferedWriter(new FileWriter(path))) {
            out.write(content);
            out.flush();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
